<template>
	<section class="margin-table">
	  <div class="module-opera" >
	    <el-form :model="searchForm" :rules="rules" ref="searchForm" label-width="170px" >
	      <el-form-item label="品牌名称：">
	        <el-autocomplete
             v-model="searchForm.region"
             icon='search'
             :fetch-suggestions="querySearchAsync"
             placeholder="请输入品牌名称"
             @select="handleSelect"
           ></el-autocomplete>
	      </el-form-item>

	      <el-form-item label="sku关键词：" prop="name">
	        <el-input @blur='varify' :maxlength='30' v-model="searchForm.name" style='width: 265px;'></el-input>
	      </el-form-item>

        <el-form-item label="平台：" prop="type">
          <el-checkbox-group v-model="searchForm.type">
            <el-checkbox :disabled='searchCan.indexOf("1")>0' label="京东" name="type"></el-checkbox>
            <el-checkbox :disabled='searchCan.indexOf("2")>0' label="一号店" name="type"></el-checkbox>
            <el-checkbox :disabled='searchCan.indexOf("3")>0' label="淘宝" name="type"></el-checkbox>
            <el-checkbox :disabled='searchCan.indexOf("4")>0' label="天猫" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

	      <el-form-item label="白名单低价区间：">
	        <input class="input" type='text' placeholder="" v-model="searchForm.price1" style='width: 160px;'></input>
	        &nbsp;&nbsp;----&nbsp;&nbsp;
	        <input class="input" type='text' placeholder="" v-model="searchForm.price2" style='width: 160px;'></input>
	        &nbsp;&nbsp;元
	      </el-form-item>

	      <el-form-item label="非白名单低价区间：">
	        <input class="input" type='text' placeholder="" v-model="searchForm.price3" style='width: 160px;'></input>
	        &nbsp;&nbsp;----&nbsp;&nbsp;
	        <input class="input" type='text' placeholder="" v-model="searchForm.price4" style='width: 160px;'></input>
	        &nbsp;&nbsp;元
	      </el-form-item>

	      <el-form-item label="假货价格区间：">
	        <input class="input" type='text' placeholder="" v-model="searchForm.price5" style='width: 160px;'></input>
	        &nbsp;&nbsp;----&nbsp;&nbsp;
	        <input class="input" type='text' placeholder="" v-model="searchForm.price6" style='width: 160px;'></input>
	        &nbsp;&nbsp;元
	      </el-form-item>

        <el-form-item label="搜索方式：" prop='search'>
          <el-radio-group v-model="searchForm.search">
             <el-radio label="品牌+关键词"></el-radio>
             <el-radio label="关键词"></el-radio>
           </el-radio-group>
        </el-form-item>

	      <el-form-item label="备注：">
	        <el-input type="textarea" v-model="searchForm.text" placeholder='请输入备注' style='width: 370px;height:210px;' :maxlength='200'></el-input>
	      </el-form-item>
	      
	      <div class="bottom-btn" style="margin-left:200px;">
	          <el-button @click="submitForm(searchForm,1)" size="small">继续添加</el-button>
	          <el-button @click="submitForm(searchForm,2)"  type="primary" size="small">提交</el-button>
	      </div>

	    </el-form>
	  </div>
	</section>
</template>
<script>
    import Vue from 'vue'
    import {mapGetters} from 'vuex'
    import {Row, Col, Form, FormItem, Tooltip, Input, Select, Option, DatePicker, ButtonGroup, Tree,Button, Table, TableColumn, Checkbox, CheckboxGroup, Message, MessageBox, Pagination, Dialog, Autocomplete,RadioGroup ,Radio
    } from 'element-ui'

    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Input);
    Vue.use(Select);
    Vue.use(Option);
    Vue.use(DatePicker);
    Vue.use(ButtonGroup);
    Vue.use(Button);
    Vue.use(Table);
    Vue.use(TableColumn);
    Vue.use(Checkbox);
    Vue.use(CheckboxGroup);
    Vue.use(Pagination);
    Vue.use(Tooltip);
    Vue.use(Dialog);
    Vue.use(Tree);
    Vue.use(Autocomplete);
    Vue.use(Radio);
    Vue.use(RadioGroup);

    Vue.prototype.$message = Message;

    export default {
      head(){
          return {
              title: "添加关键词",
              meta: [
                  { hid: 'keywordadd', name: 'keywordadd', content: 'keywordadd'}
              ]
          }
      },
      data() {
      	return {
      		tabName: '添加关键词',
          submitType: '',
          searchId: '',
          add: '',
          searchCan: '',
          brandList: [],
          searchForm: {
            region: '',
            name: '',
            type: [],
            search: '',
            price1: '',
            price2: '',
            price3: '',
            price4: '',
            price5: '',
            price6: '',
            text: '',
          },
          rules: {
            region: [
              { required: true, message: '请选择品牌名称', trigger: 'change' },
              { required: true, message: '请选择品牌名称', trigger: 'blur' }
            ],
            name: [
              { required: true, message: '请输入sku关键词', trigger: 'blur' },
              { min: 0, max: 30, message: '长度不得超过 30 字符', trigger: 'blur' }
            ],
            type: [
              { type: 'array', required: true, message: '请至少选择一个平台', trigger: 'change' }
            ],
            search: [
              { required: true, message: '请选择一种搜索方式', trigger: 'change' }
            ],
          }
      	}
      },
      watch: {
        searchForm: {
          deep:true,//深度复制
          handler: function (val, oldVal) {
            // if (parseInt(this.searchForm.price1) > parseInt(this.searchForm.price2)) {
            //   this.searchForm.price2 = this.searchForm.price1
            // }
            // if (parseInt(this.searchForm.price3) > parseInt(this.searchForm.price4)) {
            //   this.searchForm.price4 = this.searchForm.price3
            // }
            // if (parseInt(this.searchForm.price5) > parseInt(this.searchForm.price6)) {
            //   this.searchForm.price5 = this.searchForm.price6
            // }
            // if (parseInt(this.searchForm.price6) > parseInt(this.searchForm.price3)) {
            //   this.searchForm.price6 = this.searchForm.price3
            // }
            // if (parseInt(this.searchForm.price6) > parseInt(this.searchForm.price1)) {
            //   this.searchForm.price6 = this.searchForm.price1
            // }
            this.searchForm.price1 = this.searchForm.price1.replace(/[^\-?\d.]/g,'')
            this.searchForm.price2 = this.searchForm.price2.replace(/[^\-?\d.]/g,'')
            this.searchForm.price3 = this.searchForm.price3.replace(/[^\-?\d.]/g,'')
            this.searchForm.price4 = this.searchForm.price4.replace(/[^\-?\d.]/g,'')
            this.searchForm.price5 = this.searchForm.price5.replace(/[^\-?\d.]/g,'')
            this.searchForm.price6 = this.searchForm.price6.replace(/[^\-?\d.]/g,'')
          },
        }
      },
      computed: {
          ...mapGetters({
              'pageTabsList': 'getPageTabsList',
              'currentPage': 'currentPageKeyword',
              'totalCount': 'totalCountKeyword',
              'pageSize': 'pageSizeKeyword',
          })
      },
      methods: {
        varify() {
          if (this.searchId!='') {
            this.$store.dispatch('varify',{
              brandId: this.searchId,
              keywordName: this.searchForm.name,
            }).then((res)=>{
              if (res.data.data.length>0) {
                res.data.data.map(data=>{
                  this.searchCan = this.searchCan + ',' + data.platType
                  this.searchForm.search = data.searchTypeText
                  this.searchForm.type.push(data.platTypeText)
                })
              }
            })
          }
        },
        getBrandList(val) {
          this.$store.dispatch('getSelfBrandsListchu').then((res)=>{
            if (res) {
              this.brandList = res.data.data
              this.brandList.map(list=>{
                Vue.set(list,'value',list.brandName)
              })
            }
          })
        },
        querySearchAsync(queryString, cb) {
          var restaurants = this.brandList;
          var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
          cb(results);
        },
        createStateFilter(queryString) {
          return (state) => {
            return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        },
        handleSelect(item) {
          this.searchId = item.id
        },
        submitForm(searchForm,i) {
          this.submitType = i
          this.$refs.searchForm.validate((valid) => {
            if (valid) {
             this.addKeywords()
            } else {
             return false;
            }
          });
        },
        addKeywords() {
          if (parseFloat(this.searchForm.price1)>parseFloat(this.searchForm.price2) || parseFloat(this.searchForm.price3)>parseFloat(this.searchForm.price4) || parseFloat(this.searchForm.price5)>parseFloat(this.searchForm.price6) || parseFloat(this.searchForm.price6)>parseFloat(this.searchForm.price1) || parseFloat(this.searchForm.price6)>parseFloat(this.searchForm.price3)) {
            this.$message({
              message: '请输入正确的价格区间',
              type: 'error'
            });
            
          }else {
            if (
              ((this.searchForm.price1 == '' && this.searchForm.price2=='') || 
                          (this.searchForm.price1 != '' && this.searchForm.price2!='')) && 
              ((this.searchForm.price3 == '' && this.searchForm.price4=='') || 
                                        (this.searchForm.price3 != '' && this.searchForm.price4!='')) && 
              ((this.searchForm.price5 == '' && this.searchForm.price6=='') || 
                            (this.searchForm.price5 != '' && this.searchForm.price6!=''))) {
              if (this.name!='') {
                let num = 0
                this.brandList.map(list=>{
                  if (list.brandName==this.searchForm.region) {
                    this.searchId = list.id
                    num = 1
                  }
                })
                if (num==0) {
                  this.$message({
                    message: '品牌名称与ID不匹配，请从下拉框选取',
                    type: 'error'
                  });
                }else {
                  let platType = []
                  this.searchForm.type.map(type=>{
                    switch (type) {
                      case '京东':
                        platType.push(1)
                        break;
                      case '一号店':
                        platType.push(2)
                        break;
                      case '淘宝':
                        platType.push(3)
                        break;
                      case '天猫':
                        platType.push(4)
                        break;
                    }
                  })
                  let search = ''         
                  switch (this.searchForm.search) {
                    case '品牌+关键词':
                      search = 2
                      break;
                    case '关键词':
                      search = 1
                      break;
                  }

                  this.$store.dispatch('addKeywords',{
                    brandId: this.searchId,
                    keywordName: this.searchForm.name,
                    whiteLowDown: this.searchForm.price1,
                    whiteLowUp: this.searchForm.price2,
                    lowDown: this.searchForm.price3,
                    lowUp: this.searchForm.price4,
                    fakeDown: this.searchForm.price5,
                    fakeUp: this.searchForm.price6,
                    platIds: platType.join(),
                    searchType: search,
                    remark: this.searchForm.text,
                  }).then((res)=>{
                    if (res) {
                      if (this.submitType == 1) {
                        this.$router.go(0)
                      }else {
                        this.$message({
                          message: '提交成功',
                          type: 'success'
                        });
                        this.$router.push({path:'/keyWord'})
                      }
                    }            
                  })
                }
                
              }else {
                this.$message({
                  message: '请输入品牌名称',
                  type: 'error'
                });
              }  
            }else {
              this.$message({
                  message: '请完整填写某一价格区间高低价',
                  type: 'error'
                });
            }                      
          }          
        }
      },
      created () {  
          //pageTab
          if(process.BROWSER_BUILD) {
              if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                  let arr = this.pageTabsList;
                  arr[arr.length-1].name = this.tabName;
                  this.$store.commit('PAGETABSLIST',{data:arr})
              }
          }
          this.getBrandList()   
      }
    }

</script>
<style lang="scss">
  .margin-table {
    margin-top: 20px;
  }
  .el-textarea__inner {
    height: 100%;
  }
  .input {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #bfcbd9;
    box-sizing: border-box;
    color: #1f2d3d;
    display: block;
    font-size: inherit;
    height: 36px;
    line-height: 1;
    padding: 3px 10px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    width: 160px;
    display: inline-block;
    outline: none;
    &:focus {
      border-color: rgb(32,160,255);
    }
  }
</style>